package com.icebergteam.warfacewidget.ui.configuration;

import android.support.v4.app.Fragment;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import com.icebergteam.warfacewidget.AppManager;
import com.icebergteam.warfacewidget.core.LocaleManager;
import com.icebergteam.warfacewidget.core.LogManager;
import com.icebergteam.warfacewidget.core.settings.NewsSettings;
import com.icebergteam.warfacewidget.core.utils.TimeDateUtils;
import com.icebergteam.warfacewidget.news.ui.NewsActivity;
import com.icebergteam.warfacewidget.R;

public class PrefsNewsFragment extends Fragment implements PrefsFragment	{
	public static final String className = NewsActivity.class.getCanonicalName();
	//
	public static final int FRAGMENT_ID = 1;
	//
	private NewsSettings	newsSettings;
	private LocaleManager	localeManager;
	private LinearLayout	prefsContainer;
	// Active views
	private CheckBox	autoupdateNews;
	private TextView	updatePeriod;
	private CheckBox	newsFromSite;
	private CheckBox	rssThumbnails;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		
		try {
			localeManager = AppManager.getLocaleManager();
			newsSettings = AppManager.getNewsSettings();
		} catch (Exception e) {
			LogManager.LogE(className, LogManager.getExecuteMethodName(), e.getMessage());
			e.printStackTrace();
		}
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		
		ScrollView mainView = (ScrollView)inflater.inflate(R.layout.prefs_template_layout, container, false);
		
		prefsContainer = (LinearLayout) mainView.findViewById(R.id.prefs_main_layout);
		prefsContainer.addView(inflater.inflate(R.layout.prefs_news_autoupdate_layout,	prefsContainer, false));
		prefsContainer.addView(inflater.inflate(R.layout.prefs_news_display_layout,		prefsContainer, false));
		
		setViews();
		try {
			setValues();
		} catch (Exception e) {
			LogManager.LogE(className, LogManager.getExecuteMethodName(), e.getMessage());
			e.printStackTrace();
		}
				
		return mainView;
	}

	@Override
	public void setViews() {
		autoupdateNews	= (CheckBox) prefsContainer.findViewById(R.id.prefs_news_autoupate_rss_checkBox);
		updatePeriod	= (TextView) prefsContainer.findViewById(R.id.prefs_news_autoupate_period_textView);
		newsFromSite	= (CheckBox) prefsContainer.findViewById(R.id.prefs_news_display_news_from_site_checkBox);
		rssThumbnails	= (CheckBox) prefsContainer.findViewById(R.id.prefs_news_display_rss_thumbnails_checkBox);
	}

	@Override
	public void setValues() throws Exception	{
		autoupdateNews.setChecked(newsSettings.isRSSAutoupdate());
		
		String currentUpdatePeriod = String.format("%d", newsSettings.getRSSUpdatePeriod())
											+ " "
											+ localeManager.getLocalizedHours(newsSettings.getRSSUpdatePeriod());
		
		updatePeriod.setText(currentUpdatePeriod);
		newsFromSite.setChecked(newsSettings.isDisplayNewsFromSite());
		rssThumbnails.setChecked(newsSettings.isRSSThumbnails());
		
		blockDependedViews();
		newsSettings.save();
	}
	
	private void blockDependedViews()	{
		// Block depended views
		View v;
		v = (View)prefsContainer.findViewById(R.id.prefs_news_autoupate_period_field);
		v.setEnabled(newsSettings.isRSSAutoupdate());
		v.setVisibility(newsSettings.isRSSAutoupdate() ? View.VISIBLE : View.GONE);
	}

	@Override
	public boolean checkFields(View v) throws Exception {
		ConfigurationActivity.startTapFieldAnimation(v);
		switch(v.getId())	{
		// News autoupdate
		case R.id.prefs_news_autoupdate_rss_field:
			setRSSAutoupdate();
			break;
		// Update period
		case R.id.prefs_news_autoupate_period_field:
			showSelectUpdatePeriodDialog();
			break;
		// News from site
		case R.id.prefs_news_display_news_from_site_field:
			setDisplayNewsFromSite();
			break;
		// RSS thumbnails
		case R.id.prefs_news_display_rss_thumbnails_field:
			setRSSThumbnails();
			break;
		default:
			return false;
		}
		setValues();
		return true;
	}

	// RSS autoupdate
	private void setRSSAutoupdate() {
		newsSettings.setRSSAutoupdate(!newsSettings.isRSSAutoupdate());
		LogManager.LogV(PrefsNewsFragment.className, LogManager.getExecuteMethodName(), newsSettings.isRSSAutoupdate());
		newsSettings.setRSSLastUpdateTimestamp(TimeDateUtils.getCurrentTimestamp());
	}

	// Display news from site 
	private void setDisplayNewsFromSite() {
		newsSettings.setDisplayNewsFromSite(!newsSettings.isDisplayNewsFromSite());
	}
	
	// RSS thumbnails
	private void setRSSThumbnails() {
		newsSettings.setRSSThumbnails(!newsSettings.isRSSThumbnails());
	}	
	
	// Update period
	private View getUpdadtePeriodLayout() throws Exception	{
		// Setup layout
		LayoutInflater li = LayoutInflater.from(getActivity());
		View v = li.inflate(R.layout.prefs_seekbar_dialog_layout, null);
		// Setup seekbar
		SeekBar updatePeriodSeekBar = (SeekBar) v.findViewById(R.id.prefs_news_autoupate_period_dialog_seekbar);
		updatePeriodSeekBar.setMax(newsSettings.getMaxUpdatePeriod() - newsSettings.getMinUpdatePeriod());
		updatePeriodSeekBar.setProgress(newsSettings.getRSSUpdatePeriod() - newsSettings.getMinUpdatePeriod());
		// Setup text views
			// Setup current value
		TextView currentValue = (TextView) v.findViewById(R.id.prefs_seekbar_current_value_textView);
		String updatePeriod = String.format("%d", newsSettings.getRSSUpdatePeriod())
				+ " "
				+ localeManager.getLocalizedHours(newsSettings.getRSSUpdatePeriod());
		currentValue.setText(updatePeriod);	
			// Setup min value
		TextView minValue = (TextView) v.findViewById(R.id.prefs_seekbar_min_value_textView);
		minValue.setText(String.format("%d", newsSettings.getMinUpdatePeriod()));
			// Setup max value
		TextView maxValue = (TextView) v.findViewById(R.id.prefs_seekbar_max_value_textView);
		maxValue.setText(String.format("%d", newsSettings.getMaxUpdatePeriod()));
		// Setup seekbar listener
		updatePeriodSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress,
					boolean fromUser) {
				View v = (View) seekBar.getParent();
				TextView currentValue = (TextView) v.findViewById(R.id.prefs_seekbar_current_value_textView);
				
				try {
					String updatePeriod = String.format("%d", progress + newsSettings.getMinUpdatePeriod())
							+ " "
							+ localeManager.getLocalizedHours(progress + newsSettings.getMinUpdatePeriod());
					currentValue.setText(updatePeriod);	
				} catch (Exception e) {
					LogManager.LogE(className,LogManager.getExecuteMethodName(), e.getMessage());
					e.printStackTrace();
				}
					
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
				// Do nothing
				
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
				// Do nothing		
			}
		});
		
		return v;
	}
	
	private void showSelectUpdatePeriodDialog() throws Exception {
		 View updatePeriodLayout = getUpdadtePeriodLayout(); // TODO: Make this method in class
		 
		
		AlertDialog.Builder ad = new AlertDialog.Builder(getActivity())
			.setTitle(R.string.prefs_news_group_autoupdate_period_desc)
			.setCancelable(true)
		// Add items
			.setView(updatePeriodLayout)
		// Add buttons
			.setNegativeButton(R.string.dialog_cancel, new OnClickListener()	{
		
				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						setValues();
						dialog.cancel();
					} catch (Exception e) {
						LogManager.LogE(className, LogManager.getExecuteMethodName(), e.getMessage());
						e.printStackTrace();
					}
				}
			})
			.setPositiveButton(R.string.dialog_ok, new OnClickListener()	{

				@Override
				public void onClick(DialogInterface dialog, int which) {
					try {
						SeekBar updatePeriodSeekBar = (SeekBar) ((AlertDialog) dialog).findViewById(R.id.prefs_news_autoupate_period_dialog_seekbar);
						newsSettings.setRSSUpdatePeriod(updatePeriodSeekBar.getProgress() + newsSettings.getMinUpdatePeriod());
						setValues();
						dialog.cancel();
					} catch (Exception e) {
						LogManager.LogE(className, LogManager.getExecuteMethodName(), e.getMessage());
						e.printStackTrace();
					}					
				}
			});
		// Show
		ad.show();
	}	
}
